import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { TokenResult, UserInfoResult } from '@/types/member'

// 定义 Store
export const useMemberStore = defineStore(
  'member',
  () => {
    // 会员信息
    const profile = ref<TokenResult>()

    // 用户信息
    const userInfo = ref<UserInfoResult>()

    // 保存会员信息，登录时使用
    const setProfile = (val: TokenResult) => {
      profile.value = val
    }

    const getProfile = () => {
      return profile.value
    }

    // 清理会员信息，退出时使用
    const clearProfile = () => {
      profile.value = undefined
    }

    const setUserInfo = (val: UserInfoResult) => {
      userInfo.value = val
    }
    // 清理会员信息，退出时使用
    const clearUserInfo = () => {
      userInfo.value = undefined
    }

    const setCollectCount = (count: number, tag: boolean) => {
      if (tag) {
        if (userInfo.value && userInfo.value.member) {
          userInfo.value.member.collectCount += count
        }
      } else {
        if (userInfo.value && userInfo.value.member) {
          userInfo.value.member.collectCount -= count
        }
      }
    }

    const setCouponCount = (count: number) => {
      if (userInfo.value && userInfo.value.member) {
        userInfo.value.member.couponCount += count
      }
    }
    const getUserInfo = () => userInfo.value as UserInfoResult

    const setSign = (num: number) => {
      if (userInfo.value && userInfo.value.member) {
        userInfo.value.member.signStatus = 1
        userInfo.value.member.points += num
      }
    }

    // 记得 return
    return {
      profile,
      userInfo,
      getProfile,
      setSign,
      clearUserInfo,
      getUserInfo,
      setCouponCount,
      setCollectCount,
      setUserInfo,
      setProfile,
      clearProfile,
    }
  },
  {
    persist: {
      storage: {
        // ✅ 写入时：附加过期时间
        setItem(key, value) {
          try {
            const val = JSON.parse(value)
            if (val?.profile?.expires_in) {
              // 假设 expires_in 是 token 的有效秒数
              const now = new Date().getTime()
              const expiresAt = now + val.profile.expires_in * 1000 // 转为毫秒
              val._expiresAt = expiresAt // 添加过期时间戳
            }
            uni.setStorageSync(key, JSON.stringify(val))
          } catch (e) {
            uni.setStorageSync(key, value)
          }
        },

        // ✅ 读取时：检查是否过期
        getItem(key) {
          try {
            const value = uni.getStorageSync(key)
            if (!value) return null

            const val = JSON.parse(value)

            // 检查是否有 _expiresAt
            if (val?._expiresAt) {
              const now = new Date().getTime()
              if (now > val._expiresAt) {
                // ✅ 已过期，清除并返回 null
                uni.removeStorageSync(key)
                return null
              }
            }

            // 返回有效数据（但不返回 _expiresAt 字段）
            const { _expiresAt, ...rest } = val
            return JSON.stringify(rest)
          } catch (e) {
            return uni.getStorageSync(key)
          }
        },
      },
    },
  },
)
